package com.jiao.table.jdbc;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.jiao.table.annotation.IgnoreColunm;
import com.jiao.table.config.CacheDataLoad;
import com.jiao.table.entity.TableInfo;

import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author Vincent.jiao
 * @Date 2022/6/6 11:44
 */
public class SQLBuilder {
    public static String getSelectAllSql(String tableName) {
        return " select "+(getAllColunm(tableName))+" from " + tableName;
    }

    public static String getSelectByPrimaryKeySql(String tableName) {
        TableInfo tableInfo = CacheDataLoad.getTableInfo(tableName);
        if(tableInfo == null) {
            return null;
        }

        return getSelectAllSql(tableName) + " where " + tableInfo.getPrimaryKeyName() +" = ?";
    }

    public static String getDeleteByPrimaryKeySql(String tableName) {
        TableInfo tableInfo = CacheDataLoad.getTableInfo(tableName);
        if(tableInfo == null) {
            return null;
        }

        return "  delete from " + tableName + " where " + tableInfo.getPrimaryKeyName() +" = ?";
    }

    private static String getAllColunm(String tableName) {
        Class clazz = CacheDataLoad.getTableEntityClass(tableName);
        if(clazz == null) {
            return null;
        }

        List<String> allColunm = new LinkedList<>();
        for (Field field : clazz.getDeclaredFields()){
            IgnoreColunm ignoreColunm = field.getAnnotation(IgnoreColunm.class);
            if(ignoreColunm == null) {
                allColunm.add(field.getName());
            }
        }

        return CollectionUtil.join(allColunm, ", ");
    }
}
